<?php
/**
 * Register user
 * @param email     varchar
 * @param password  varchar
 */
require_once('rb.php');
R::setup('mysql:host=ftp.giemiebier.nl:3306;dbname=personify', 'school', 'admin123');

$return = array();

if (isset($_POST['email']) && $_POST['email'] != ""
    && isset($_POST['password']) && $_POST['password'] != "") {

    $count = R::count("users","emailaddress = ?",array($_POST['email']));
    if($count > 0){
        $return['register'] = false;
        $return['error'] = "Account bestaat al";
    }else{
        createUser();
        $return['register'] = true;
        $_SESSION['login'] = true;
        $id = getID( $_POST['email']);
        $_SESSION['id'] = $id;
        $return['id'] = $id;
    }

}else{
    $return['register'] = false;
    $return['error'] = "Geen email en/of wachtwoord opgegeven";
}

echo json_encode($return);

function createUser(){
    $user = R::dispense("users");
    $user->emailaddress = $_POST['email'];
    $user->password = makeHash($_POST['password']);
    $user->datecreated = date('Y-m-d H:i:s');
    R::store($user);
}

function getID($email){
    $user = R::findOne("users","emailaddress=?",array($email));
    if($user == null){
        return null;
    }
    return $user->id;
}


function makeHash($var) {
    $iterations = 10;
    $salt = '$1$qiejdren$';
    $hash = crypt($var, $salt);
    for ($i = 0; $i < $iterations; ++$i) {
        $hash = crypt($hash . $var, $salt);
    }
    return $hash;
}

?>